package com.yp.infrastructure.common.model;

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.lang.NonNull;

import java.io.Serializable;
import java.lang.reflect.Constructor;

/**
 * 实体类基类
 */
@Data
@Slf4j
@SuperBuilder(toBuilder = true)
@NoArgsConstructor
public abstract class BaseModel implements Serializable {

    public <T extends BaseModel> T from(@NonNull Object obj) {
        BeanUtils.copyProperties(obj, this);
        @SuppressWarnings("unchecked")
        T t = (T) this;
        return t;
    }

    public static <T extends BaseModel> T newInstance(Class<T> clazz) {
        try {
            @SuppressWarnings("unchecked")
            Constructor<T>[] constructors = (Constructor<T>[]) clazz.getDeclaredConstructors();
            Constructor<T> constructor = null;
            for (Constructor<T> item : constructors) {
                int parameterCount = item.getParameterCount();
                if (parameterCount == 0) {
                    constructor = item;
                    break;
                }
            }
            if (constructor == null) {
                log.error("no constructor found.");
                return null;
            }
            return constructor.newInstance();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

}
